using Cysharp.Threading.Tasks;
using DG.Tweening;
using Light;
using UnityEngine;
using UnityEngine.UI;

namespace Dream.FirstLevel
{
    //mao 24-11-24 03:45
    /// <summary>
    ///     负责进行一个产品处理
    /// </summary>
    public class Producter : MonoBehaviour
    {
        [SerializeField] private string productName; //对处理的产品进行分类 
        [SerializeField] private bool isUsing; //检查该物体是否正在使用

        [SerializeField] private Image circleOutline; //转动进度条

        //开始音频
        [Header("刚交互时候播放的音频")] [SerializeField]
        private AudioClip startAudioClip;

        //结束音频
        [Header("完成时播放的音频")] [SerializeField] private AudioClip endAudioClip;

        private bool isTouching; //检查物体是否接触

        private Collider2D playerCollider; //暂存玩家碰撞体

        private void Awake()
        {
            circleOutline = transform.parent.Find("Canvas/CircleLine").GetComponent<Image>();
            circleOutline.gameObject.SetActive(false);
        }

        private async void Update()
        {
            //靠近的同时并检查
            if (isTouching && !isUsing && Input.GetKeyDown(KeyCode.J))
            {
                isUsing = true;
                var list = playerCollider.GetComponent<Player.Player>()._waitingProducts;
                foreach (var productBase in list)
                    //检查该产品没有完成并且是该Producter可以处理的
                    if (!productBase.isComplated && productBase.GetType().Name == productName)
                    {
                        AudioManager.Instance.PlaySFX(startAudioClip);
                        //调用该产品的处理方法
                        productBase.Deal();
                        StartDealAnimation(productBase.GetWaitTimeS());
                        await UniTask.Delay(productBase._waitTime);
                        circleOutline.gameObject.SetActive(false);
                        //一次只能处理一个product
                        AudioManager.Instance.PlaySFX(endAudioClip);
                        break;
                    }

                isUsing = false;
            }
        }


        private void OnTriggerEnter2D(Collider2D other)
        {
            if (other.CompareTag("Player"))
            {
                isTouching = true;
                playerCollider = other;
            }
        }


        private void OnTriggerExit2D(Collider2D other)
        {
            if (other.CompareTag("Player"))
            {
                isTouching = false;
                playerCollider = null;
            }
        }


        private void StartDealAnimation(int waitTime)
        {
            Debug.Log("StartDealAnimation");
            circleOutline.gameObject.SetActive(true);
            //转圈形式进度条加载
            circleOutline.DOFillAmount(1, waitTime).SetEase(Ease.Linear)
                .OnComplete(() => { circleOutline.fillAmount = 0; });
        }
    }
}